﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.ActiveRecord;
using Windvoice.Library;
using System.Collections;

namespace Windvoice.Blog
{
    public partial class Voice : ActiveRecordBase<Voice>
    {
        public static Voice[] GetList(int pageIndex, int pageSize, string content, out int recordCount)
        {
            if (!String.IsNullOrEmpty(content))
            {
                recordCount = FindAll().Where(v => v.Content.Contains(content)).Count();
                return FindAll().Where(v => v.Content.Contains(content)).OrderByDescending(v => v.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToArray();
            }
            else
            {
                recordCount = FindAll().Count();
                return FindAll().OrderByDescending(v => v.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToArray();
            }
        }

        public static Voice[] GetRandomVoices(int topCount)
        {
            int MaxIndex = FindAll().Count();

            if (MaxIndex <= topCount)
                topCount = MaxIndex;
            //return FindAll().ToArray();

            Voice[] Voices = FindAll().ToArray();
            ArrayList RandomArray = EnumHelper.GetIntArray(start: 0, end: topCount);

            List<Voice> VoiceList = new List<Voice>();
            int i = 0;
            while (i < topCount)
            {
                Random rand = new Random(DateTime.Now.Millisecond);
                var NextRandom = rand.Next(0, RandomArray.Count);
                var SafeRandom = Convert.ToInt32(RandomArray[NextRandom]);

                VoiceList.Add(Voices[SafeRandom]);
                RandomArray.RemoveAt(NextRandom);
                i++;
            }

            return VoiceList.ToArray();
        }

        public static string GetVoiceJson(Voice[] voices)
        {
            var json = "[";

            foreach (var voice in voices)
                json += "{" + String.Format("id:'{0}',author:'{1}',content:'{2}'", voice.ID, voice.Author, voice.Content) + "},";

            return json + "]";
        }
    }
}
